package com.adminex.controller;

import com.adminex.mapper.UserMapper;
import com.adminex.pojo.User;
import com.adminex.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class IndexController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //访问登陆页面
    @GetMapping({"/", "/login"})
    public String loginPage() {
        return "login";
    }

    @PostMapping("/login")
    public String main(User user, HttpSession session, Model model) {
        User byUsername = userMapper.selectOneByUsername(user.getUsername());
        String password = byUsername.getPassword();
        //判断是否为空
        if (StringUtils.hasLength(user.getUsername()) && StringUtils.hasLength(user.getPassword()) && password.equals(user.getPassword())) {
            //把登陆成功的用户信息存到session
            session.setAttribute("UserSession", user);

            //重定向到index.html
            return "redirect:/index.html";
        } else {
            model.addAttribute("msg", "账户或密码输入错误，请重新输入！");
            return "login";
        }

    }

    @GetMapping("/index.html")
    public String indexPage(Model model) {

        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String s = ops.get("/index.html");
        int ss = Integer.parseInt(s);
        if (ss != 1) {
            if (ss % 2 == 0) {
                ss = ss / 2;
            } else {
                ss = (ss - 1) / 2;
            }
        }
        String s1 = ops.get("/dynamic_table");
        if (s1 != null) {
            int ss1 = Integer.parseInt(s1);
            if (ss1 != 1) {
                if (ss1 % 2 == 0) {
                    ss1 = ss1 / 2;
                } else {
                    ss1 = (ss1 - 1) / 2;
                }
                model.addAttribute("dynamicCount", ss1);
            }
        }
        model.addAttribute("indexCount", ss);
        return "index";
    }
}
